<template>
  <div class="food-compare">
    <div class="page-header">
      <div class="header-content">
        <div class="back-button" @click="$router.back()">
          <div class="back-button-inner">
            <el-icon>
              <ArrowLeft />
            </el-icon>
            <span>返回</span>
          </div>
          <div class="back-button-bg"></div>
        </div>
        <h1 class="page-title">
          <span class="title-text">食品营养对比</span>
          <div class="title-decoration">
            <span class="decoration-dot"></span>
            <span class="decoration-line"></span>
          </div>
        </h1>
      </div>
      <div class="header-wave">
        <svg viewBox="0 0 1440 120" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M0,0 C320,80 420,80 740,40 C1060,0 1360,80 1440,120 L1440,0 L0,0 Z" fill="rgba(66, 99, 235, 0.1)" />
        </svg>
      </div>
    </div>

    <div class="compare-content">
      <div class="section-header">
        <h2 class="section-title">营养概览</h2>
        <div class="section-subtitle">对比食品的主要营养成分</div>
      </div>

      <div class="foods-container">
        <div class="background-decoration">
          <div class="deco-circle"></div>
          <div class="deco-line"></div>
          <div class="deco-dots">
            <div class="dot"></div>
            <div class="dot"></div>
            <div class="dot"></div>
          </div>
        </div>

        <div v-for="(food, index) in compareData" :key="food.foodId" class="food-card">
          <div class="food-image-wrapper">
            <div class="food-image">
              <el-image :src="food.picture" :alt="food.foodName" fit="cover" :preview-src-list="[food.picture]" />
            </div>
            <div class="food-rank" v-if="isWinnerFood(food)">
              <div class="rank-badge">
                <el-icon>
                  <Trophy />
                </el-icon>
                <span>营养之王</span>
              </div>
              <div class="rank-ribbon"></div>
            </div>
          </div>
          <div class="food-info">
            <div class="food-header">
              <div class="food-title">
                <h2 class="food-name">{{ food.foodName }}</h2>
                <div class="food-category" v-if="food.category">
                  <el-tag size="small" type="success" effect="dark">{{ food.category }}</el-tag>
                </div>
              </div>
              <div class="food-number">{{ index + 1 }}</div>
            </div>
            <p class="food-description">{{ food.description }}</p>
            <div class="food-highlights">
              <div class="highlight-item" v-for="(highlight, idx) in getHighlights(food)" :key="idx">
                <div class="highlight-value">{{ highlight.value }}{{ highlight.unit }}</div>
                <div class="highlight-label">{{ highlight.label }}</div>
              </div>
            </div>
            <div class="food-tags" v-if="food.tags && food.tags.length">
              <el-tag v-for="tag in food.tags" :key="tag" size="small" effect="plain" class="food-tag">
                {{ tag }}
              </el-tag>
            </div>
          </div>
          <div class="food-decoration">
            <div class="decoration-dot"></div>
            <div class="decoration-line"></div>
          </div>
        </div>
      </div>

      <div class="comparison-details">
        <div class="section-header">
          <h2 class="section-title">详细对比</h2>
          <div class="section-subtitle">各营养成分的具体含量对比</div>
        </div>
        <h2 class="section-title">详细对比</h2>
        <div class="comparison-tabs" v-if="compareData.length >= 2">
          <div v-for="(tab, index) in tabs" :key="index" class="tab-item" :class="{ active: currentTab === index }"
            @click="currentTab = index">
            {{ tab.name }}
          </div>
        </div>

        <div class="comparison-items" v-if="getCurrentTabItems.length > 0">
          <div v-for="(item, index) in displayedItems" :key="index" class="comparison-item"
            :class="{ 'fade-in': index >= 9 }">
            <div class="item-header">
              <div class="item-info">
                <span class="item-name">{{ item.name }}</span>
                <el-tooltip :content="item.description" placement="top">
                  <el-icon class="info-icon">
                    <InfoFilled />
                  </el-icon>
                </el-tooltip>
              </div>
              <div class="item-bars">
                <div v-for="(food, foodIndex) in compareData" :key="foodIndex" class="bar-container"
                  :class="{ 'is-winner': isHighestValue(item, foodIndex) }">
                  <div class="bar" :style="{ width: getBarWidth(item, foodIndex) }">
                    <span class="bar-value">{{ getItemValue(item, foodIndex) }}{{ item.unit }}</span>
                  </div>
                </div>
              </div>
            </div>
            <div class="item-analysis" v-if="compareData.length >= 2">
              <el-icon>
                <TrendCharts />
              </el-icon>
              {{ getAnalysis(item) }}
            </div>
          </div>

          <div v-if="getCurrentTabItems.length > 9 && !showAll" class="show-more-button" @click="toggleShowAll">
            <span>显示更多</span>
            <el-icon>
              <ArrowDown />
            </el-icon>
          </div>

          <div v-if="showAll && getCurrentTabItems.length > 9" class="show-more-button collapse" @click="toggleShowAll">
            <span>收起</span>
            <el-icon>
              <ArrowUp />
            </el-icon>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  ArrowLeft,
  Trophy,
  InfoFilled,
  TrendCharts,
  ArrowDown,
  ArrowUp
} from '@element-plus/icons-vue'
import { getFoodNutritionService } from '@/api/food.js'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const compareData = ref([])
const currentTab = ref(0)
const showAll = ref(false)

const tabs = computed(() => {
  if (!compareData.value || compareData.value.length === 0) {
    return [{
      name: '加载中...',
      items: []
    }]
  }

  // 从第一个食品数据中获取所有营养成分类别
  const categories = new Set()
  compareData.value[0].nutritionComponents?.forEach(comp => {
    if (comp.category) {
      categories.add(comp.category)
    }
  })

  const categoryTabs = Array.from(categories).map(category => ({
    name: category,
    items: compareData.value[0].nutritionComponents
      ?.filter(comp => comp.category === category)
      .map(comp => ({
        name: comp.nameCn,
        nameEn: comp.nameEn,
        unit: comp.unit,
        description: comp.description || `${comp.nameCn}含量`
      })) || []
  }))

  // 如果没有分类，返回默认分类
  return categoryTabs.length > 0 ? categoryTabs : [{
    name: '营养成分',
    items: compareData.value[0].nutritionComponents?.map(comp => ({
      name: comp.nameCn,
      nameEn: comp.nameEn,
      unit: comp.unit,
      description: comp.description || `${comp.nameCn}含量`
    })) || []
  }]
})

const getCurrentTabItems = computed(() => {
  if (!tabs.value || !tabs.value[currentTab.value]) {
    return []
  }
  return tabs.value[currentTab.value].items || []
})

// 判断是否是营养最佳的食品
const isWinnerFood = (food) => {
  if (!compareData.value || compareData.value.length < 2) return false

  // 计算每个食品的营养得分
  const scores = compareData.value.map(f => {
    let score = 0
    let total = 0
    if (!f.nutritionComponents) return { food: f, score: 0, total: 0 }

    f.nutritionComponents.forEach(comp => {
      total++
      if (comp.status === 1) score++ // 正常状态加分
    })
    return { food: f, score, total }
  })

  // 计算得分率
  scores.forEach(item => {
    item.rate = item.total > 0 ? item.score / item.total : 0
  })

  // 按得分率排序
  scores.sort((a, b) => b.rate - a.rate)

  // 如果最高分相同，不显示胜出者
  if (scores.length >= 2 && scores[0].rate === scores[1].rate) {
    return false
  }

  return food === scores[0].food
}

// 获取食品亮点数据
const getHighlights = (food) => {
  if (!food || !food.nutritionComponents) return []

  const highlights = []

  // 蛋白质
  const protein = food.nutritionComponents.find(n => n.nameEn === 'protein')
  if (protein) {
    highlights.push({
      value: protein.content,
      unit: protein.unit,
      label: '蛋白质'
    })
  }

  // 热量
  const energy = food.nutritionComponents.find(n => n.nameEn === 'energy')
  if (energy) {
    highlights.push({
      value: energy.content,
      unit: energy.unit,
      label: '热量'
    })
  }

  return highlights
}

// 判断是否是最高值
const isHighestValue = (item, index) => {
  if (!compareData.value || !compareData.value[index]) return false

  const values = compareData.value.map(food => {
    const comp = food.nutritionComponents?.find(n => n.nameEn === item.nameEn)
    return parseFloat(comp?.content || 0)
  })
  const currentValue = values[index]
  return currentValue === Math.max(...values)
}

// 获取营养成分值
const getItemValue = (item, index) => {
  const food = compareData.value[index]
  if (!food || !food.nutritionComponents) return '0'

  const comp = food.nutritionComponents.find(n => n.nameEn === item.nameEn)
  return comp?.content || '0'
}

// 计算进度条宽度
const getBarWidth = (item, index) => {
  const values = compareData.value.map(food => {
    const comp = food.nutritionComponents.find(n => n.nameEn === item.nameEn)
    return parseFloat(comp?.content || 0)
  })
  const max = Math.max(...values)
  const value = values[index]
  return max === 0 ? '0%' : `${(value / max) * 100}%`
}

// 获取分析结果
const getAnalysis = (item) => {
  if (!compareData.value || compareData.value.length < 2) {
    return '数据加载中...'
  }

  const values = compareData.value.map((food, index) => ({
    name: food.foodName || `食品${index + 1}`,
    value: parseFloat(getItemValue(item, index))
  })).filter(v => v.name && !isNaN(v.value))

  if (values.length < 2) {
    return '暂无对比数据'
  }

  // 检查是否所有值都相同
  const firstValue = values[0].value
  const allSame = values.every(v => v.value === firstValue)
  if (allSame) {
    return `${item.name}含量相同`
  }

  // 找出最高值
  values.sort((a, b) => b.value - a.value)
  return `${values[0].name}的${item.name}含量最高`
}

// 获取食品数据
const getFoodData = async () => {
  try {
    const foodIds = route.query.foods?.split(',')
    if (!foodIds || foodIds.length < 2) {
      ElMessage.error('参数错误')
      router.push('/category')
      return
    }

    const numericIds = foodIds.map(id => parseInt(id))
    console.log('发送的数据:', numericIds)

    const result = await getFoodNutritionService(numericIds)
    console.log('接收的数据:', result)

    // 确保数据结构正确
    if (result.data && Array.isArray(result.data)) {
      compareData.value = result.data.map(food => ({
        ...food,
        nutritionComponents: Array.isArray(food.nutritionComponents)
          ? food.nutritionComponents
          : []
      }))
      console.log('处理后的数据:', compareData.value)
    } else {
      throw new Error('数据格式不正确')
    }
  } catch (error) {
    console.error('获取对比数据失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
      ElMessage.error(`获取对比数据失败: ${error.response.data.message || error.message}`)
    } else {
      ElMessage.error('获取对比数据失败')
    }
  }
}

// 监听数据变化
watch(compareData, (newData) => {
  console.log('数据更新:', newData)
}, { deep: true })

// 计算要显示的项目
const displayedItems = computed(() => {
  if (showAll.value) {
    return getCurrentTabItems.value
  }
  return getCurrentTabItems.value.slice(0, 9)
})

// 切换显示状态的方法
const toggleShowAll = () => {
  showAll.value = !showAll.value
}

onMounted(() => {
  if (route.query.foods) {
    getFoodData()
  }
})
</script>

<style scoped>
.food-compare {
  padding: 32px;
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f9ff 0%, #f8fafc 100%);
  position: relative;
  overflow: hidden;
}

.page-header {
  position: relative;
  margin: -32px -32px 48px -32px;
  padding: 48px 32px 32px;
  background: linear-gradient(135deg, #ffffff 0%, #f0f7ff 100%);
  border-bottom: none;
}

.header-content {
  position: relative;
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 2;
}

.back-button {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  perspective: 1000px;
}

.back-button-inner {
  position: relative;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  color: #4263eb;
  font-size: 15px;
  font-weight: 500;
  background: white;
  border-radius: 25px;
  box-shadow: 0 4px 15px rgba(66, 99, 235, 0.15);
  transition: all 0.3s ease;
  z-index: 2;
}

.back-button-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #4263eb;
  border-radius: 25px;
  transform: translateZ(-10px);
  opacity: 0;
  transition: all 0.3s ease;
}

.back-button:hover .back-button-inner {
  color: white;
  transform: translateZ(20px);
  background: #4263eb;
}

.back-button:hover .back-button-bg {
  opacity: 0.2;
  transform: translateZ(-20px);
}

.back-button .el-icon {
  font-size: 18px;
  transition: transform 0.3s ease;
}

.back-button:hover .el-icon {
  transform: translateX(-4px);
}

.page-title {
  text-align: center;
  position: relative;
  margin: 0;
  padding-bottom: 16px;
}

.title-text {
  font-size: 36px;
  font-weight: 700;
  background: linear-gradient(135deg, #1a1f36 0%, #4263eb 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  display: inline-block;
}

.title-decoration {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  gap: 8px;
}

.decoration-dot {
  width: 6px;
  height: 6px;
  background: #4263eb;
  border-radius: 50%;
  display: inline-block;
}

.decoration-line {
  width: 40px;
  height: 2px;
  background: linear-gradient(90deg, #4263eb, transparent);
  display: inline-block;
}

.header-wave {
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 100%;
  line-height: 0;
  z-index: 1;
}

.header-wave svg {
  width: 100%;
  height: auto;
}

.section-header {
  text-align: center;
  margin-bottom: 32px;
}

.section-title {
  font-size: 28px;
  font-weight: 600;
  color: #1a1f36;
  margin: 0 0 8px;
}

.section-subtitle {
  font-size: 16px;
  color: #6b7280;
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: 0;
}

.deco-circle {
  position: absolute;
  width: 300px;
  height: 300px;
  border-radius: 50%;
  background: radial-gradient(circle, rgba(66, 99, 235, 0.1) 0%, rgba(66, 99, 235, 0) 70%);
  top: -100px;
  right: -100px;
}

.deco-line {
  position: absolute;
  width: 100%;
  height: 1px;
  background: repeating-linear-gradient(90deg,
      #e5e7eb,
      #e5e7eb 6px,
      transparent 6px,
      transparent 12px);
  top: 50%;
  transform: translateY(-50%);
}

.deco-dots {
  position: absolute;
  display: flex;
  gap: 12px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #4263eb;
  opacity: 0.2;
}

.foods-container {
  position: relative;
  margin-bottom: 40px;
  display: flex;
  justify-content: center;
  gap: 32px;
  flex-wrap: wrap;
  padding: 20px 0;
}

.food-card {
  position: relative;
  width: 300px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  overflow: hidden;
  z-index: 1;
  backdrop-filter: blur(8px);
  flex-shrink: 0;
}

.food-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.food-image-wrapper {
  position: relative;
  border-bottom: 1px solid #f3f4f6;
  width: 100%;
  height: 260px;
}

.food-image {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.food-image :deep(img) {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.food-card:hover .food-image :deep(img) {
  transform: scale(1.05);
}

.food-rank {
  position: absolute;
  top: 20px;
  left: -8px;
  z-index: 2;
}

.rank-badge {
  background: #10b981;
  color: white;
  padding: 8px 16px;
  border-radius: 0 20px 20px 0;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
  box-shadow: 2px 4px 12px rgba(16, 185, 129, 0.2);
}

.rank-badge :deep(.el-icon) {
  font-size: 18px;
  color: #fbbf24;
}

.rank-ribbon {
  position: absolute;
  left: 0;
  bottom: -8px;
  width: 8px;
  height: 8px;
  background: #059669;
  clip-path: polygon(0 0, 100% 0, 100% 100%);
}

.food-info {
  padding: 24px;
}

.food-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.food-title {
  flex: 1;
}

.food-number {
  width: 36px;
  height: 36px;
  background: #4263eb;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  font-weight: 600;
  margin-left: 16px;
}

.food-name {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 8px;
  color: #1a1f36;
}

.food-category {
  margin-bottom: 12px;
}

.food-description {
  font-size: 14px;
  color: #6b7280;
  margin: 0 0 20px;
  line-height: 1.6;
}

.food-highlights {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-bottom: 20px;
  background: rgba(248, 250, 252, 0.8);
  padding: 20px;
  border-radius: 12px;
  position: relative;
  overflow: hidden;
  backdrop-filter: blur(4px);
}

.food-highlights::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(90deg, #4263eb, #10b981);
}

.highlight-item {
  text-align: center;
  min-width: 100px;
}

.highlight-value {
  font-size: 20px;
  font-weight: 600;
  color: #4263eb;
  margin-bottom: 4px;
}

.highlight-label {
  font-size: 14px;
  color: #6b7280;
}

.food-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.food-tag {
  margin-right: 0;
}

.food-decoration {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 4px;
  overflow: hidden;
}

.decoration-dot {
  position: absolute;
  bottom: -4px;
  left: 50%;
  transform: translateX(-50%);
  width: 12px;
  height: 12px;
  background: #4263eb;
  border-radius: 50%;
}

.decoration-line {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, transparent, #4263eb, transparent);
}

.comparison-details {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(8px);
  border: 1px solid rgba(229, 231, 235, 0.5);
  padding: 32px;
  border-radius: 16px;
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.06);
}

.section-title {
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 24px;
  color: #1a1f36;
}

.comparison-tabs {
  display: flex;
  gap: 2px;
  background: #f1f5f9;
  padding: 4px;
  border-radius: 12px;
  margin-bottom: 32px;
}

.tab-item {
  flex: 1;
  padding: 12px 24px;
  text-align: center;
  font-weight: 500;
  color: #64748b;
  cursor: pointer;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.tab-item.active {
  background: white;
  color: #4263eb;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.comparison-items {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.comparison-item {
  background: #f8fafc;
  border-radius: 12px;
  padding: 24px;
}

.item-header {
  display: flex;
  align-items: center;
  gap: 32px;
  margin-bottom: 16px;
}

.item-info {
  width: 160px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.item-name {
  font-weight: 500;
  color: #1a1f36;
}

.info-icon {
  color: #64748b;
  cursor: help;
}

.item-bars {
  flex: 1;
  display: flex;
  gap: 24px;
}

.bar-container {
  flex: 1;
  height: 32px;
  background: rgba(0, 0, 0, 0.04);
  border-radius: 16px;
  overflow: hidden;
}

.bar {
  height: 100%;
  background: #e2e8f0;
  border-radius: 16px;
  transition: width 0.6s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
}

.bar-container.is-winner .bar {
  background: #4263eb;
}

.bar-value {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #1a1f36;
  font-size: 14px;
  font-weight: 500;
}

.bar-container.is-winner .bar-value {
  color: white;
}

.item-analysis {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #64748b;
  font-size: 14px;
}

.item-analysis .el-icon {
  color: #4263eb;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.food-card {
  animation: fadeIn 0.6s ease-out forwards;
}

.food-card:nth-child(2) {
  animation-delay: 0.2s;
}

.food-card:nth-child(3) {
  animation-delay: 0.4s;
}

.food-highlights:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(66, 99, 235, 0.12);
}

.comparison-details {
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.comparison-details:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.08);
}

.show-more-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 16px;
  margin-top: 16px;
  background: #f8fafc;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #4263eb;
  font-weight: 500;
}

.show-more-button:hover {
  background: #f0f7ff;
  transform: translateY(-2px);
}

.show-more-button.collapse {
  background: #eef2ff;
}

.show-more-button .el-icon {
  transition: transform 0.3s ease;
}

.show-more-button:hover .el-icon {
  transform: translateY(2px);
}

.show-more-button.collapse:hover .el-icon {
  transform: translateY(-2px);
}

.comparison-item {
  transition: all 0.3s ease;
}

.fade-in {
  animation: slideDown 0.3s ease forwards;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
